package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.MeterSizeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.MeterSize;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS11006Srvl
 */

public class CS11006Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
    private Database db;
	private String vaUrlAddress;
	private String vaAgentBrowser;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11006Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		String vaProcessType = request.getParameter("process_type");
		
		if(vaProcessType.equals("insert")){ 
			 insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else{
			getDataTable(request,response);
		}
	
    	
    }
    public void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	this.db = new Database();
		String  vaCodeId = request.getParameter("id");
		
		MeterSizeDAO  voMeterSizeDAO =new MeterSizeDAO(db);
		try {
			db.beginTransaction();
			voMeterSizeDAO.deleteMeterSizeByMeterSizeCode(vnSiteId,vaCodeId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11006", JDate.getDate(), JDate.getTime(),vnUserId, "CS11006Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		
		response.getWriter().write("Success Data");
		
    	
    }
    public void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
	
		String vaCodeId = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		double vnFee = Integer.parseInt(request.getParameter("fee"));
		String vaOldCodeId = request.getParameter("oldCodeID");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		MeterSizeDAO  voMeterSizeDAO = new MeterSizeDAO(db);
		String vaFeeDupicate = voMeterSizeDAO.findsMeterSizeCodeBySiteAndMeterSizeCode(vnSiteId, vaOldCodeId, vaCodeId);
	
		if(vaFeeDupicate==null){
					
			MeterSize meterSize = new MeterSize();
			meterSize.setVnSiteId(vnSiteId);
			meterSize.setVaMeterSizeCode(vaCodeId);
			meterSize.setVaRequestType("**");
			meterSize.setVaReceiveCode("**");
			meterSize.setVaDescription(vaDesp);
			meterSize.setVnFee(vnFee);
			meterSize.setVnUpdateUserId(vnUserId);
			meterSize.setVaUpdateDate(vaDate);
			meterSize.setVaUpdateTime(vaTime);
			
			try {
				db.beginTransaction();
				voMeterSizeDAO.updateMeterSize(vnSiteId,vaOldCodeId, meterSize);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11006", JDate.getDate(), JDate.getTime(),vnUserId, "CS11006Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			} finally{
				db.close();
			}
	    	response.getWriter().write("success");
	    	
		}else{
			db.close();
			response.getWriter().write("MeterCodeId_dupicate");
		}
		
		
    	
    }
    public void insert(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();

		String vaCodeId = request.getParameter("id");
		String vaDesp = request.getParameter("desp");
		double vnFee =Double.parseDouble(request.getParameter("fee"));
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		MeterSizeDAO voMeterSizeDAO = new MeterSizeDAO(db);
		String vaFeeDupicate = voMeterSizeDAO.findMeterSizeCodeBySiteAndMeterSizeCode(vnSiteId, vaCodeId);
		
		if(vaFeeDupicate==null){
			
			MeterSize meterSize = new MeterSize();
			meterSize.setVnSiteId(vnSiteId);
			meterSize.setVaMeterSizeCode(vaCodeId);
			meterSize.setVaRequestType("**");
			meterSize.setVaReceiveCode("**");
			meterSize.setVaDescription(vaDesp);
			meterSize.setVnFee(vnFee);
			meterSize.setVnInsertUserId(vnUserId);
			meterSize.setVaInsertDate(vaDate);
			meterSize.setVaInsertTime(vaTime);
			
			try {
				db.beginTransaction();
		    	voMeterSizeDAO.addMeterSize(meterSize);
		    	db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11006", JDate.getDate(), JDate.getTime(),vnUserId, "CS11006Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			} finally{
				db.close();
			}
	    	
	    	response.getWriter().write("success");
	    	
		}else{
			db.close();
			response.getWriter().write("MeterCodeId_dupicate");
		}
		
    	
    }
    public void edit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db  = new Database();
		
		String pnMeterCodeId = request.getParameter("id");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		this.db = new Database();
		MeterSizeDAO  voMeterSize = new MeterSizeDAO(db);
		//daoMeterSize.findDescriptionBySiteAndCode(vnSiteId,pnMeterCodeId);
		
		JSONObject voJsonObject = new JSONObject();
		voJsonObject.put("id" , pnMeterCodeId);
		voJsonObject.put("desp", voMeterSize.findDescriptionAndFeeBySiteAndCode(vnSiteId, pnMeterCodeId, "DESCRIPTION"));
		voJsonObject.put("fee",  voMeterSize.findDescriptionAndFeeBySiteAndCode(vnSiteId, pnMeterCodeId, "FEE"));
		
		PrintWriter voOut = response.getWriter();
		
		db.close();
		//System.out.println(jsonObject.toJSONString());
		voOut.print(voJsonObject.toJSONString());
    	
    }
    
    public void getDataTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		MeterSizeDAO  voMeterSize = new MeterSizeDAO(db);
		
		List<Map<String , Object>> voListFindAll;
		voListFindAll = voMeterSize.findMeterSizeBySiteId(vnSiteId);
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> voMapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(voMapItem.get("METER_SIZE_CODE"));
			voColumn.add(voMapItem.get("DESCRIPTION"));
			voColumn.add(voMapItem.get("FEE"));
			voRow.add(voColumn);
		}
		
		voObject.put("iTotalRecords", voListFindAll.size());
		voObject.put("iTotalDisplayRecords", voListFindAll.size());
		voObject.put("aaData", voRow);
	
		db.close();
		voOut.print(voObject.toJSONString());
    	
    }
    		
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);	
	}

}
